package cn.tenghw.redission.controller;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA2021.3
 * @Author: Tenghw
 * @Date: 2022/11/10  13:04
 * @Description:
 */
@RestController
@RequestMapping("/redisLock")
@SuppressWarnings("all")
public class RedisLockController {
        /**
     * 这2个注入，是根据name来找的，而不是根据类型，所以用@Resource，而不是用Autowired
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redisson;

    //商品在redis缓存中的key
    private static final String REDIS_KEY = "redis_oa_01";
    //商品的总库存数量
    private static final int MAX_SIZE = 400;

    /**
     * 初始化库存总数=400
     */
    //@PostMapping("/init")
    @PostConstruct //在构造函数执行完之后执行
    public void init() {
        stringRedisTemplate.opsForValue().set(REDIS_KEY, String.valueOf(MAX_SIZE));
        System.out.printf("==================初始化库存总数=400===================");
    }

    /**
     * 扣减库存业务
     */
    @PostMapping("/reduceStock")
    public void reduceStock() {
        //redisson分布式锁
        String lockKey = "product001";
        RLock lock = redisson.getLock(lockKey);
        try {
            lock.lock();//获取锁
            int s = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(REDIS_KEY)));
            if(s>0){
                s--;
                if(s==0){
                    System.out.printf("1号服务扣减库存成功，库存全部清空了"  + "\n");
                }else{
                    System.out.printf("1号服务扣减库存成功，剩余库存为：" + s + "\n");
                }
                stringRedisTemplate.opsForValue().set(REDIS_KEY, String.valueOf(s));
            }else {
                System.out.printf("1号服务：库存不足："+ "\n");
            }
        } catch (Exception e) {
            System.out.printf("1号服务：catch...."+ "\n");
        } finally {
            //释放锁
            lock.unlock();
        }
    }
}